package com.putong35.common.httprequest.retrofit;

import android.content.Context;
import android.util.Log;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.putong35.common.httprequest.retrofit.converter.HttpError;
import com.putong35.common.app.BaseApplication;
import com.putong35.common.app.data.HttpCommonApi;
import com.putong35.common.httprequest.HttpRequest;
import com.putong35.common.httprequest.IHttpRequest;
import com.putong35.common.httprequest.UrlParams;
import com.putong35.common.httprequest.responsecallbacks.BaseResponseListener;
import com.putong35.common.utils.SLog;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;


public class RetrofitHttp implements IHttpRequest {
    public static final String TAG = RetrofitHttp.class.getSimpleName();

    private Context mContext;

    public RetrofitHttp(Context context) {
        mContext = context;
    }

    @Override
    public void get(String url, UrlParams params, final BaseResponseListener cb) {
        get(url, params, null, cb);
    }

    @Override
    public void get(String url, UrlParams params, final Map<String, String> headParams, final BaseResponseListener cb) {
        if (url.contains("tpshop")) {
            return;
        }

        String paramUrl = UrlParams.getUrlWithQueryString(url, params);
        SLog.e(HttpRequest.TAG, paramUrl);

        Retrofit retrofit = BaseApplication.retrofit();
        HttpCommonApi request = retrofit.create(HttpCommonApi.class);

        HashMap<String, String> hashMap = new HashMap<>();
        if (params != null && params.getUrlParamMap().size() > 0) {
            for (Map.Entry<String, String> entry : params.getUrlParamMap().entrySet()) {
                hashMap.put(entry.getKey(), entry.getValue());
            }
        }

        Call<ResponseBody> call = request.httpGet(url, hashMap);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
                Log.d(TAG, "onResponse: ");
                try {
                    String bodyStr = response.body().string();
                    cb.deliverResponse(bodyStr);
                    Log.d(TAG, "onResponse: ");
                } catch (Exception e) {
                    e.printStackTrace();
                    onFailure(call, e);
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable throwable) {
                throwable.printStackTrace();
                int code = -1;
                if (throwable instanceof HttpError) {
                    HttpError error = ((HttpError) throwable);
                    if (error.body instanceof ResponseData) {
                        ResponseData data = ((ResponseData) error.body);
                        code = data.code;
                    }

                }
                Log.d(TAG, "onFailure: " + throwable.getMessage());
                if (cb != null) {
                    cb.deliverFailureResponse(throwable, code, throwable.getMessage());
                }
            }
        });


    }

    @Override
    public void post(String url, UrlParams params, final BaseResponseListener cb) {
        post(url, params, null, cb);
    }

    @Override
    public void post(String url, UrlParams params, Map<String, String> headerParams, final BaseResponseListener cb) {
        SLog.e(HttpRequest.TAG, url);

    }

    @Override
    public void post(String url, JSONObject jsonObject, final BaseResponseListener cb) {
        post(url, jsonObject, null, cb);
    }

    @Override
    public void post(String url, JSONObject jsonObject, final Map<String, String> headParams, final BaseResponseListener cb) {
        SLog.e(HttpRequest.TAG, url);

    }


    @Override
    public void put(String url, JSONObject jsonObject, final BaseResponseListener cb) {
        put(url, jsonObject, null, cb);
    }

    @Override
    public void put(String url, JSONObject jsonObject, final Map<String, String> headParams, final BaseResponseListener cb) {
        SLog.e(HttpRequest.TAG, url);

    }


    @Override
    public void delete(String url, UrlParams params, BaseResponseListener cb) {
        delete(url, params, null, cb);
    }

    @Override
    public void delete(String url, UrlParams params, final Map<String, String> headParams, BaseResponseListener cb) {
        String paramUrl = UrlParams.getUrlWithQueryString(url, params);
        SLog.e(HttpRequest.TAG, paramUrl);

    }


    @Override
    public void finish() {
      /*  if (mRequest != null) {
            mRequest.cancel();
        } else {
            SLog.e(HttpRequest.TAG, "Cancel failed, no request exist!!!");
        }*/
    }


    /**
     * http response success
     *
     * @param response
     * @param cb
     */
    private void deliverResponse(String response, BaseResponseListener cb) {
        SLog.e(HttpRequest.TAG, "function --> deliverResponse: msg == " + response);
        cb.deliverResponse(response);
    }


    private void deliverErrorResponse(VolleyError error, BaseResponseListener cb) {
        SLog.e(HttpRequest.TAG, "function --> deliverErrorResponse");
        if (cb != null) {
            String errorMsg = "";
            if (error != null && error.networkResponse != null && error.networkResponse.data != null) {
                errorMsg = new String(error.networkResponse.data);
            }
            int errorNo = com.putong35.common.httprequest.Response.ERR_CODE_INVALID_NET;
            if (error != null && error.networkResponse != null) {
                errorNo = error.networkResponse.statusCode;
            }
            SLog.e(HttpRequest.TAG, "function --> onDeliverFailureResponse: msg == " + errorMsg + "  errorNo == " + errorNo);
            cb.deliverFailureResponse(error, errorNo, errorMsg);
        }
    }


    public class XResponseListener<T> implements Response.Listener<T> {
        BaseResponseListener mListener;

        public XResponseListener(BaseResponseListener cb) {
            mListener = cb;
        }

        @Override
        public void onResponse(T t) {
            String responseStr = null;
            if (t instanceof JSONObject) {
                JSONObject jobj = (JSONObject) t;
                responseStr = jobj.toString();
            } else if (t instanceof String) {
                responseStr = (String) t;
            }
            deliverResponse(responseStr, mListener);
        }
    }


    public class XErrorResponseListener implements Response.ErrorListener {
        BaseResponseListener mListener;

        public XErrorResponseListener(BaseResponseListener cb) {
            mListener = cb;
        }

        @Override
        public void onErrorResponse(VolleyError volleyError) {
            deliverErrorResponse(volleyError, mListener);
        }
    }

}

